package com.cdy.server.netty;

import com.cdy.common.response.DownloadResponse;
import com.cdy.common.response.Response;
import com.cdy.common.serialize.HessionSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端编码
 * Created by 陈东一
 * 2019/10/20 0020 20:47
 */
@Slf4j
@ChannelHandler.Sharable
public class ServerEncodeHandler extends MessageToByteEncoder<Response> {
    
    private final HessionSerialize serialize = new HessionSerialize();

    @Override
    protected void encode(ChannelHandlerContext ctx, Response msg, ByteBuf out) throws Exception {
        log.info("server encode {}",msg.toString());

        if (msg instanceof DownloadResponse) {
            ByteBuf buf = ((DownloadResponse) msg).getByteBuf();
            ((DownloadResponse) msg).setByteBuf(null);
            byte[] serialize = this.serialize.serialize((DownloadResponse) msg, DownloadResponse.class);
            out.writeInt(serialize.length + Math.toIntExact(((DownloadResponse) msg).getLength()));
            out.writeInt(serialize.length);
            out.writeBytes(serialize);
            out.writeBytes(buf);
        } else {
            byte[] serialize = this.serialize.serialize(msg, Response.class);
            out.writeInt(serialize.length);
            out.writeInt(serialize.length);
            out.writeBytes(serialize);
        }
    }

}
